package com.eian.boot.web.interceptor;

import com.eian.boot.common.core.adapter.TtlMDCAdapter;
import com.eian.boot.common.core.constants.SystemConstants;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author alex.meng
 * @createTime 2025-09-05 14:51
 * @description 拦截注入链路ID
 */
@Component
public class TraceIdInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 尝试从请求头获取traceId（用于跨服务传递）
        String traceId = request.getHeader(SystemConstants.TRACE_ID_HEADER);
        if (StringUtils.isBlank(traceId)) {
            traceId = TtlMDCAdapter.generateTraceId();
        }

        // 存入TTL和MDC
        TtlMDCAdapter.put(SystemConstants.TRACE_ID_MDC_KEY, traceId);
        // 将traceId设置到响应头，方便前端追踪
        response.setHeader(SystemConstants.TRACE_ID_HEADER, traceId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
        // 请求完成后清理上下文，防止内存泄漏
        TtlMDCAdapter.clear();
    }
}